package com.tony.scheduler.server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;

import org.apache.log4j.Logger;
import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.filter.logging.LoggingFilter;
import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
import org.springframework.beans.factory.InitializingBean;

public class SchedulerServer implements InitializingBean {

    public static final Logger logger = Logger.getLogger("engine.log");

    private SchedulerHandler   schedulerHandler;

    public void initSchedulerServer() throws IOException {

        IoAcceptor acceptor = new NioSocketAcceptor();
        acceptor.getFilterChain().addLast("logger", new LoggingFilter());
        acceptor.getFilterChain().addLast("codec",
            new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));
        acceptor.setHandler(schedulerHandler);
        acceptor.setDefaultLocalAddress(new InetSocketAddress(9123));
        acceptor.bind();
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        if (logger.isInfoEnabled()) {
            logger.info("begine to start init schedulerserver ");
        }
        initSchedulerServer();

        if (logger.isInfoEnabled()) {
            logger.info("start init schedulerclient success");
        }
    }

    public void setSchedulerHandler(SchedulerHandler schedulerHandler) {
        this.schedulerHandler = schedulerHandler;
    }

}
